class node {
  constructor(ele) {
    this.ele = ele // 内容
    this.next = null // 指针
  }
}

class linkedList {
  constructor() {
    this.head = new node('head') // 头节点
  }

  find(item) {
    let currentNode = this.head // head对象
    while (currentNode.ele !== item) {
      if (currentNode.next === null) {
        return null // 如果找不到节点，返回 null
      }
      currentNode = currentNode.next // 指针指向下一个节点
    }
    return currentNode
  }

  insert(newEle, item) {
    let newNode = new node(newEle)

    let currentNode = this.find(item)
    if (currentNode === null) {
      return
    }

    newNode.next = currentNode.next
    currentNode.next = newNode

    // 如果插入的节点指向头节点，形成环
    if (this.find(newEle)) {
      let targetNode = this.find(newEle)

      if (targetNode) {
        newNode.next = targetNode
      }
    }
  }

  remove(item) {
    let currentNode = this.head

    // 有下一个元素，不能是item元素本身
    while (currentNode.next !== null && currentNode.next.ele !== item) {
      currentNode = currentNode.next
    }
    if (currentNode.next !== null) {
      currentNode.next = currentNode.next.next
    }
  }

  update(item, newItem) {
    let currentNode = this.find(item)
    if (currentNode === null) {
      return
    }
    currentNode.ele = newItem
  }
}

export default linkedList
